package com.itcast.googleplay.fragment;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.view.View;
import android.widget.ListView;

import com.itcast.googleplay.R;
import com.itcast.googleplay.adapter.MyBaseAdapter;
import com.itcast.googleplay.domain.Category;
import com.itcast.googleplay.domain.CategoryInfo;
import com.itcast.googleplay.holder.BaseHolder;
import com.itcast.googleplay.holder.CategoryHolder;
import com.itcast.googleplay.holder.CategoryTitleHolder;
import com.itcast.googleplay.protocol.CategoryProtocol;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;


public class CategoryFragment extends BaseFragment {
	private List<Category> categoryList;
	private MyAdapter myAdapter;

	@Override
	public ResultState onSubLoad() {
		CategoryProtocol categoryProtocol = new CategoryProtocol();
		categoryList = categoryProtocol.getData("category", 0, "");
		if(categoryList!=null){
			if(categoryList.size()>0){
				return ResultState.STATE_SUCCESSED;
			}
			return ResultState.STATE_EMPTY;
		}
		return ResultState.STATE_ERROR;
	}

	@Override
	public View onCreateSubSuccessedView() {
		View view = UIUtils.inflate(R.layout.layout_listview_category);
		ListView lvCategory = (ListView) view.findViewById(R.id.lv_category);
		List<Object> list = new ArrayList<Object>();
		//对数据进行重构
		for (Category category : categoryList) {
			list.add(category.title);
			//切记
//			list.add(category.infos);
			list.addAll(category.infos);
		}
		
		myAdapter = new MyAdapter(list);
		lvCategory.setAdapter(myAdapter);
		//拿数据填充控件
		return view;
	}
	
	class MyAdapter extends MyBaseAdapter<Object>{
		//此状态码指向(图片+文字)listView条目
		private static final int CATEGORY_ITEM = 0;
		//此状态码指向listView标题条目
		private static final int CATEGORY_ITEM_TITLE = 1;

		//1.告知数据适配器有2中展示条目的方式
		@Override
		public int getViewTypeCount() {
			return 2;
		}
		
		//2,指定特定索引的展示状态码
		@Override
		public int getItemViewType(int position) {
			Object object = list.get(position);
			if(object instanceof CategoryInfo){
				//object对象是不是CategoryInfo类型的
				return CATEGORY_ITEM;
			}else{
				//object对象是不是String类型的
				return CATEGORY_ITEM_TITLE;
			}
		}

		public MyAdapter(List<Object> list) {
			super(list);
		}

		@Override
		public BaseHolder getSubBaseholder() {
			int type = getItemViewType(currentPosition);
			
			if(type == CATEGORY_ITEM){
				//生成一般条的holder
				return new CategoryHolder();
			}else{
				//生成只有title的holder
				return new CategoryTitleHolder();
			}
		}
		
	}
}
